package com.bree.erp.jsf.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.bree.erp.entity.ItemRequest;
import com.bree.erp.service.ItemRequestService;
import com.bree.erp.service.ItemRequestWrapperService;

public class ItemRequestWrapperServiceBean implements ItemRequestWrapperService {

	private ItemRequestService itemRequestService;
	private Long prId;
	private List<ItemRequest> cachedList;

	public ItemRequestWrapperServiceBean(ItemRequestService itemRequestService,
			Long prId) {
		this.itemRequestService = itemRequestService;
		this.prId = prId;
	}

	@Override
	public ItemRequest read(Long id) {
		ItemRequest template = new ItemRequest();
		template.setId(id);
		
		if(cachedList == null) {
			list();
		}
		
		int idx = cachedList.indexOf(template);
		return cachedList.get(idx);
	}

	@Override
	public Collection<ItemRequest> list() {

		if (cachedList == null) {
			cachedList = new ArrayList<ItemRequest>(
					itemRequestService.list(prId));
		}
		
		int count = 0;
		for(ItemRequest item : cachedList) {
			item.setItemNumber(++count);
		}

		return cachedList;
	}

	@Override
	public void addItem(ItemRequest item) {

		if (cachedList != null) {
			cachedList.add(item);
		}

	}

	@Override
	public void removeItem(ItemRequest item) {
		if (cachedList != null) {
			int index = cachedList.indexOf(item);
			if (index >= 0) {
				cachedList.remove(index);
			}
		}

	}

	@Override
	public void updateQuantity(ItemRequest itemRequest, double quantity) {
		
		if (cachedList != null) {
			
			int idx = cachedList.indexOf(itemRequest);
			if(idx >= 0) {
				cachedList.get(idx).setQuantity(quantity);
			}
			
		}
	}

}
